package pyf.demo2;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 多线程下载
 */
public class DownImgDemo implements Runnable {
    private String url;
    private String fileName;

    DownImgDemo(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    public static void main(String[] args) {
        new Thread(new DownImgDemo("https://blog.gitee.com/wp-content/uploads/2020/02/logo_blog_light.png", "下载1"), "下载1").start();
        new Thread(new DownImgDemo("https://blog.gitee.com/wp-content/uploads/2020/02/logo_blog_light.png", "下载2"), "下载2").start();
        new Thread(new DownImgDemo("https://blog.gitee.com/wp-content/uploads/2020/02/logo_blog_light.png", "下载3"), "下载3").start();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
        try {
            new DownFile().down(url, fileName + ".jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class DownFile {

        public void down(String url, String fileName) throws IOException {
            URL url1 = new URL(url);
            FileUtils.copyURLToFile(url1, new File("d:/img/" + fileName));
        }
    }
}
